<template>
    <div>
        <page-header @toLastPage="toLastPage">
            <template v-slot:title>
                发起群聊
            </template>
        </page-header>
        <div class="header-search">
    <van-field
        v-model="search"
        left-icon="search"
        placeholder="搜索"
    />
        </div>
        <div class="content">
            <div class="chooseBox van-hairline--top" @click="chooseOneGroup">选择一个群</div>
            <div class="chooseBox van-hairline--top" @click="faceToFaceGroup">面对面建群</div>
    <van-index-bar>
    <van-checkbox-group v-model="result" checked-color='#07C160'>
  <div v-for="(item,index) in newFriendsList" :key="index">
    <div>
      <van-index-anchor :index="item.index" />
<div v-for="(item1,index1) in item.information" :key="index1">
    <van-cell value="">
  <!-- 使用 title 插槽来自定义标题 -->
    <template #title >
        <van-checkbox :name='item1.F_FriendID'>
             <van-image
            width="1.5rem"
            height="1.5rem"
            radius=".2rem"
            fit="cover"
            class="f-center"
            :src="item1.avatar"
            />
            <span class="nickname">{{item1.name}}</span>
        </van-checkbox>
    </template>
  </van-cell>
</div>
    </div>
  </div>
  </van-checkbox-group>
</van-index-bar>
        </div>
        <div class="bottom van-hairline--bottom">
            <div class="right"><van-button type="primary" size="small" :disabled='disabled' @click="setShowDialog">
                <span>完成</span>
                <span v-if="result.length!==0">({{result.length}})</span>
                </van-button></div>
        </div>
        <!-- 弹出框 -->
        <van-dialog v-model="showDialog" title="群信息" show-cancel-button confirmButtonText='创建' confirmButtonColor='#07C160' @confirm='createGroup'>
           <div class="groupAvatar flex">
                <div class='text f-center'>群聊头像</div>
  <van-uploader v-model="groupAvatar"  :preview-full-image='false' :deletable='false' :show-upload=isUpload :after-read='afterRead' preview-size='3rem' />
           </div>
           <div class="groupName">
        <van-field v-model="groupName" label="群聊名称" placeholder="为新建的群命名吧~~"/>
           </div>
           </van-dialog>
        <!-- 加载组件 -->
        <loading v-if="showLoading"></loading>
    </div>
</template>
<script>
import pageHeader from '../common/pageHeader';
import {Meteor} from 'meteor/meteor';
import { friends,image, messages,user } from '../../../api/collections/index';
import loading from '../common/loading';
import upload from '../../../api/libs/upload';
var pinyin = require("pinyin");
export default {
    components:{
        pageHeader,
        loading
    },
    meteor: {
    $subscribe: {
      'userInf': []
    },
    friendsList(){
       let listArr = friends.find({F_UserID:this.id}).fetch()
        if(listArr.length>0){
        let newArr = []
       let index = 0
         listArr.forEach(e => {
           Meteor.call('image.find',e.F_FriendAvatarId,(err,res)=>{
             if(err){
               this.$toast(err.error)
             }
             else{
               e.avatar = res.base64
               const userInf = user.findOne({_id:e.F_FriendID})
            let check = e.F_beizhu?e.F_beizhu:userInf.nickname
            e.name = check
         let fristName = pinyin(check, { style: pinyin.STYLE_NORMAL, heteronym: true })[0][0].substring(0, 1).toUpperCase();
          //进行判断，给原始json数据添加新的键值对
          if (this.indexList.includes(fristName) == true) { 
           if(newArr.some((item,i) =>{if(item.index == fristName){index=i;return true}})){
             newArr[index].information.push(e)
           }
           else{
             let arr = []
             arr.push(e)
             newArr.push({index:fristName,information:arr})
           }
          } else {
           if(newArr.some((item,i) =>{if(item.index == '#'){index=i;return true}})){
             newArr[index].information.push(e)
           }
           else{
             let arr = []
             arr.push(e)
             newArr.push({index:'#',information:arr})
           }
          }
             }
           })     
        });
       return newArr
        }
    },
    groupMsgList(){
        if(this.createGroupId!==''){
            return messages.find({M_GroupId:this.createGroupId}).fetch()
        }
    }
        },
    mounted(){
        this.showLoading = false
    },
    watch:{
      friendsList(){
        if(this.friendsList.length>0){
          this.newFriendsList=[...this.friendsList]
          this.newFriendsList.sort((item1,item2)=>{
            let val1 = item1.index
            let val2 = item2.index
            if (val1 < val2) {
              return -1;
          } else if (val1 > val2) {
              return 1;
          } else {
              return 0;
          }   
          })
        }
        if(this.friendsList.length<2){
            this.$toast('当前好友人数少于2人,无法创建群聊')
        }
      },
    //   创建群聊成功时获取群消息,设置首页消息框信息
      groupMsgList(){
          let arr = [this.id,...this.result]
          if(this.groupMsgList.length==arr.length){
              let list = this.groupMsgList
            arr.forEach((e)=>{
                    list.sort((item1,item2)=>{
                        return item2.M_Time-item1.M_Time
                    })
                    this.createIndexMsg(e,list[0]._id,list)
            }) 
            this.$toast.success(this.groupName+'已创建')
            this.$router.push('/home')
          }
      }
    },
    computed:{
        disabled(){
            if(this.result.length>=2)return false
            else return true
        }
    },
    methods:{
        toLastPage(){
            this.$router.go(-1)
        },
        // 选择一个群聊
        chooseOneGroup(){

        },
        // 面对面建群
        faceToFaceGroup(){

        },
        setShowDialog(){
            this.showDialog = true
        },
        afterRead(file){
            this.isUpload = false
            upload.uploadImg(file,this.afterUpload)
        },
        afterUpload(res){
            this.groupAvatarId = res
        },
        // 创建群聊
        createGroup(){
            if(this.groupAvatar.length==0&&this.groupName==''){
                return this.$toast('创建失败，请先设置群信息')
            }else{
                // 创建群
               Meteor.call('group.create',{
                   g_name:this.groupName,
                   g_notice:'',
                   g_create_time:new Date().getTime(),
                   g_adminId:this.id,
                   g_avatarId:this.groupAvatarId
               },(err,res)=>{
                   this.createGroupId = res
                   if(err){
                       this.$toast(err.error)
                   }else{
                        let arr = [this.id,...this.result]
                       arr.forEach((e,i)=>{
                        //    创建群成员
                        const getUser = user.findOne({_id:e})
                           Meteor.call('groupUser.create',{
                               gid:this.createGroupId,
                               userId:e,
                               add_time:new Date().getTime(),
                               groupName:getUser.nickname,
                               groupRemark:'',
                               showGroupItemNIck:true
                           })
                        //    插入进群消息
                            Meteor.call('message.create',{
                                M_IsGroup:true,
                                M_PostMessages:{inviteId:this.id,inviteeId:e},
                                M_Status:false,//消息状态(0:已读，1:未读)
                                M_Time:new Date().getTime(),//消息发送时间
                                M_MessagesType:'invite',//消息类型
                                M_FromUserID:this.id,//发送者Id
                                M_ToUserID:e,//接收者Id
                                M_GroupId:this.createGroupId
                           })
                       })
                   }
               })
            }
        },
        // 创建首页消息表
        createIndexMsg(id,data,arr){
        var msg = {
        I_UserId:id,
        I_OtherId:this.createGroupId,
        I_Type:'group',
        I_LastMsgId:data,
        I_isTop:false
      }
      let num = 0
      if(arr){
        arr.forEach((e) => {
        if(e.M_Status == false&&e.M_MessagesType!=='invite'){
          num = num+1
        }
      })
      }
      msg.I_noReadCount = num
      Meteor.call('indexMsg.create',msg) 
    }
    },
    data() {
        return {
            search:'',
            id:sessionStorage.getItem('user'),
            newFriendsList:[],
            // 索引栏
            indexList:['*', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'],
            result:[],
            showLoading:true,
            showDialog:false,
            groupAvatar:[],
            isUpload:true,
            groupName:'',
            groupAvatarId:'',
            sendName:{},
            acceptName:{},
            createGroupId:'',
            lastMsgId:''
        }
    },
}
</script>
<style scoped>
    .header-search{
        position: fixed;
        top: 1.5rem;
        left: 0;
        right: 0;
        z-index: 999;
        box-shadow: 0 .05rem .05rem -.05rem #888;
    }
   .header-search .van-cell{
       padding:.3rem;
   }
    .content{
        margin-top: 3.1rem;
        margin-bottom: 3.2rem;
    }
    .chooseBox{
        padding: .5rem 0;
        font-size: .7rem;
        background-color: #fff;
        width: 100%;
    }
   .content .van-cell{
  padding: .3rem .4rem;
  line-height: 0;
}
    .nickname{
    display: inline-block;
    position: relative;
    top: -.5rem;
    font-size: .6rem;
    left: .5rem;
    }
    .bottom{
        padding:.5rem;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #f3f3f3;
    }
    .right{
        text-align: right;
    }
    .right .van-button--small{
        height: 1.2rem;
    }
    .groupAvatar{
        font-size: .6rem;
        justify-content: space-between;
        padding: 1rem;
        color: #666;
    }
    .van-uploader{
        margin-right: 2rem;
    }
</style>